package logback;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.status.ErrorStatus;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-5
 * Time: 上午9:48
 * To change this template use File | Settings | File Templates.
 */
public class LevelAppender<E>  extends RollingFileAppender<E>  {
     private List<Encoder<E>> encoderList = new ArrayList<Encoder<E>>();

    public void addEncoder(Encoder<E> encoder) {
        this.encoder = encoder;
        encoderList.add(encoder);


    }

    protected void writeOut(E event) throws IOException {
        for (Encoder<E> encoder1 : encoderList) {
            if (encoder1 instanceof  LevelPatternLayoutEncoder) {
                LevelPatternLayoutEncoder levelPatternLayoutEncoder = (LevelPatternLayoutEncoder) encoder1;
                if (event instanceof ILoggingEvent) {
                    ILoggingEvent iLoggingEvent = (ILoggingEvent)event;

                    if (iLoggingEvent.getLevel().levelStr.equalsIgnoreCase(levelPatternLayoutEncoder.getLevel())) {
                        levelPatternLayoutEncoder.doEncode(iLoggingEvent);
                    }
                }
            } else {
                encoder1.doEncode(event);
            }
        }

    }
}
